package com.lm.common.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lm.common.core.constant.CommonConstants;
import com.lm.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义没有访问权限处理类
 *
 * @author lm
 * @date 2019/4/25 10:43
 */
@Slf4j
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("没有相关权限，禁止访问，{}", request.getRequestURI());

        // 返回格式：{"code":403,"message":"没有相关权限","data":"Access is denied"}
        R<String> result = new R<>();
        result.setCode(HttpStatus.SC_FORBIDDEN);
        result.setMsg("没有相关权限，禁止访问!");
        result.setData(accessDeniedException.getMessage());

        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }

}